var express = require("express");
var router = express.Router();
var request = require("request");
var config = require("../../config");
const cache = require("memory-cache");
const codeToken = new cache.Cache();
codeToken.put("access_token", "", 7000 * 1000);
/* 获取用户的openid、unionid. */
router.get("/", function (req, res, next) {
  let token = codeToken.get("access_token");
  // 如果access_token过期（预留200秒过期时间），或者没有access_token
  if (!token) {
    // 重新获取access_token
    request(
      "https://api.weixin.qq.com/sns/oauth2/access_token?&grant_type=authorization_code&appid=" +
        config.appID +
        "&secret=" +
        config.appSecret +
        "&code=" +
        req.query.code,
      function (error, response, body) {
        res.send(body);
        // 也可以用来获取用户信息，当scope为snsapi_userinfo时
      }
    );
  } else {
    res.send({
      access_token: token,
      expires_in: 7200,
    });
  }
});

module.exports = router;
